package com.bokesoft.project.all.listener;

import java.io.File;
import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;

import com.bokesoft.yigo2.distro.yigosupport.props.preparation.Yigo2PropPreparationHelper;

/**
 * 如何使用 SpringBoot 属性替换 Yigo properties 文件中的变量 注意: 这个 Listener
 * 不能使用 @{@link Configuration} 配置, 否则执行时间可能会 落后于 Yigo 初始化的
 * <code>ServletContextBean</code>, 建议的初始化方法 建议参考 {@link StartYigoERP} .
 */
public class DynamicYigoPropsListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
	private static final Logger log = LoggerFactory.getLogger(DynamicYigoPropsListener.class);
	private boolean prepared = false;
	@Override
	public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
		if(prepared) {
			log.warn("重复进入ApplicationEnvironmentPreparedEvent事件，避免多次更新系统classpath");
			return;
		}
		final Environment env = event.getEnvironment();

		Yigo2PropPreparationHelper.setValueProvider(new Yigo2PropPreparationHelper.ValueProvider() {
			@Override
			public String getValue(String variable) {
				String value = env.getProperty(variable);
				if (variable.endsWith(".solution-path")) {
					value = StringUtils.replace(value, File.separator, "/");
				}
				return value;
			}
		});
		try {
			Yigo2PropPreparationHelper.prepare("/yigo/properties",
					"core.properties",
					"dbcp.properties",
					"druid.properties",
					"ehcache.xml",
					"Jedis.properties",
					"jta.properties",
					"lang.xml",
					"license",
					"MySQL.properties",
					"ORACLE.properties",
					"PasswordRule.xml",
					"quartz_jobs.xml",
					"quartz.properties",
					"server.properties",
					"SQL.properties",
					"xa.properties"
			);
			//DefaultResourceLoader defaultResourceLoader=new DefaultResourceLoader();
			//defaultResourceLoader.getResource("/yigo/properties")
			//Yigo2PropPreparationHelper.p
			prepared = true;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

}
